package edu.itesm.rm.scene {
	import com.greensock.easing.Linear;
	import flash.events.Event;
	import com.greensock.TweenMax;
	import away3d.materials.BitmapMaterial;
	import away3d.primitives.Plane;
	
	/**
	 * @author aldoreyes
	 */
	public class Bullet extends Plane {
		
		public static const HIT:String = "hit";
		
		[Embed(source="../../../../../assets/bullet.png")]		
		private var bulletTexture:Class;
		
		[Embed(source="../../../../../assets/enemy_bullet.png")]		
		private var enemy_bulletTexture:Class;
		
		private var bulletMaterial:BitmapMaterial;
		private var _startZ:Number;
		private var _endZ:Number;
		private var _ready:Boolean;
		private var _type:int;
		private var _size:int;
		
		public static const FRIENDLY:int = 0;
		public static const ENEMY:int = 1;
		
		
		public function set endZ(value : Number) : void {
			_endZ = value;
		}
		
		public function set startZ(value : Number) : void {
			_startZ = value;
		}
		
		public function get ready() : Boolean {
			return _ready;
		}
		
		public function Bullet(startZ:Number, endZ:Number, type:int = FRIENDLY) {
			super(getMaterial(_type=type), _size=_type==FRIENDLY?8:16, _size, 1, 1);
			_startZ = startZ;
			_endZ = endZ;
			_ready = true;
		}
		
		private function getMaterial(type:int):BitmapMaterial{
			//if(!bulletMaterial){
			if(type == FRIENDLY){
				bulletMaterial = new BitmapMaterial(new bulletTexture().bitmapData);
				
			}else{
				bulletMaterial = new BitmapMaterial(new enemy_bulletTexture().bitmapData);
			}
			bulletMaterial.transparent = true;
			//}
			
			return bulletMaterial;
		}
		
		private function shootReset():void{
			_ready = true;
		}
		
		private function shootComplete():void{
			dispatchEvent(new Event(HIT));
			TweenMax.to(this, .25, {scaleX:2, scaleY:2});
			TweenMax.to(bulletMaterial, .25, {alpha:0, onComplete:shootReset});
		}
		
		public function shoot(x:Number, y:Number):void{
			this.x = x;
			this.y = y;
			this.z = _startZ;
			this.scaleX = this.scaleY = 1;
			bulletMaterial.alpha = 1;
			TweenMax.killTweensOf(this);
			TweenMax.to(this, _type==FRIENDLY?1:4, {z:_endZ, onComplete: shootComplete, ease:Linear.easeNone});
			_ready = false;
		}
		
		public function destroy():void 
		{
			TweenMax.killTweensOf(this);
			dispose(true);
		}
		
		
	}
}
